package com.wash.shoes.domain.dy.request;

import cn.hutool.core.thread.ThreadUtil;
import com.alibaba.fastjson2.JSONObject;
import com.wash.shoes.domain.dy.model.DyRefundOrder;
import com.wash.shoes.domain.dy.model.DyRefundOrder2;
import com.wash.shoes.domain.dy.model.QueryRefundDto;
import com.wash.shoes.domain.jd.JdOrderService;
import com.wash.shoes.entity.BrandPo;
import com.wash.shoes.entity.OrderGoodPo;
import com.wash.shoes.entity.OrderPo;
import com.wash.shoes.entity.OrderTransportPo;
import com.wash.shoes.service.OrderTransportService;
import com.wash.shoes.util.WsRandomUtil;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.io.ThreadUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.wash.shoes.domain.dy.request.DyBookRequest.DY_SUCCESS_CODE;

/**
 * @author lijianguo
 * @Date 29/03/2025 08:08
 * https://developer.open-douyin.com/docs/resource/zh-CN/mini-app/develop/server/payment/trade-system/trading/refund/apply
 * /支付/交易系统/行业交易系统/退货退款/
 * 开发者发起退款
 **/
@Log4j2
@Component
public class DyRefundRequest extends DyBaseRequest {
    @Autowired
    private DyBookRequest dyBookRequest;

    @Autowired
    private JdOrderService jdOrderService;

    @Autowired
    private OrderTransportService orderTransportService;


    public void cancelJdOrder(OrderPo orderPo){
        OrderTransportPo orderTransportPo=orderTransportService.getOneByOrderId(orderPo.getId());
        if(orderTransportPo==null){
            log.info("不需要取消京东的物流");
            return;
        }
        jdOrderService.cancelJdOrder(orderTransportPo.getWayBillCode());
    }

    /**
     * 退货退款 查询退款
     */
    public String queryRefund(OrderPo orderPo) {

        QueryRefundDto queryRefundDto = new QueryRefundDto();
        queryRefundDto.setOrder_id(orderPo.getMtOrderId());
        BrandPo brandPo = getBrandPo(orderPo);
        String result = postRequest(DyConstant.QUERY_REFUND_POST, queryRefundDto, brandPo.getAccountid());
        if (DY_SUCCESS_CODE.equals(JSONObject.parseObject(result).getJSONObject("extra").getString("error_code"))) {
            boolean hasRefundList = JSONObject.parseObject(result)
                    .getJSONObject("data") != null
                    && JSONObject.parseObject(result)
                    .getJSONObject("data")
                    .getJSONArray("refund_list") != null;
            //没有refund_list表示就未退款
            if (hasRefundList) {
                return JSONObject.parseObject(result).getJSONObject("data").getJSONArray("refund_list").getJSONObject(0).getString("refund_status");
            } else {
                return "NOT_REFUND";
            }
        }
        return "QUERY_REFUND_CUSTRM_FAIL";
    }

    /**
     * 退款
     */
    public JSONObject refund(OrderPo orderPo) {

        DyRefundOrder dyRefundOrder = new DyRefundOrder();
        dyRefundOrder.setOut_order_no(orderPo.getOrderNo());

        String refundNo = orderPo.getOrderNo() + "_" + WsRandomUtil.generateByRandom(10);
        dyRefundOrder.setOut_refund_no(refundNo);
        // 退款单的跳转的 schema
        DyRefundOrder.OrderEntrySchema orderEntrySchema = new DyRefundOrder.OrderEntrySchema();
        orderEntrySchema.setPath("pages/order/detail/detail?id=" + orderPo.getId());
        JSONObject params = new JSONObject();
        params.put("id", orderPo.getId());
        orderEntrySchema.setParams(params.toString());
        dyRefundOrder.setOrder_entry_schema(orderEntrySchema);

        // 需要发起退款的商品单信息,子订单
        List<OrderGoodPo> orderGoodPoList = orderGoodService.getOrderGoods(orderPo.getId());
        List<DyRefundOrder.ItemOrderDetail> itemOrderDetailList = new ArrayList<>(orderGoodPoList.size());
        List<DyRefundOrder.RefundRelatedOrderDetail> refundRelatedOrderDetails = new ArrayList<DyRefundOrder.RefundRelatedOrderDetail>();


        for (OrderGoodPo orderGoodPo : orderGoodPoList) {
            DyRefundOrder.RefundRelatedOrderDetail dyRefundOrderDetail = new DyRefundOrder.RefundRelatedOrderDetail();
            DyRefundOrder.ItemOrderDetail itemOrderDetail = new DyRefundOrder.ItemOrderDetail();
            itemOrderDetail.setItem_order_id(orderGoodPo.getItemOrderId());
            itemOrderDetail.setRefund_amount((int) (orderGoodPo.getPrice() * 100));  //抖音这里是做了拆单，预下单这里需要注意，要拆成子订单下单，因此删除了数量
            itemOrderDetailList.add(itemOrderDetail);
            dyRefundOrderDetail.setOrder_id(orderPo.isNewBook() ? orderGoodPo.getDyBookId() : orderPo.getDyBookId());
            dyRefundOrderDetail.setRefund_amount(0);
            refundRelatedOrderDetails.add(dyRefundOrderDetail);
        }
        dyRefundOrder.setItem_order_detail(itemOrderDetailList);
        dyRefundOrder.setNotify_url("https://www.shoeswasher.com/prod-api/common/dyCallBlack/dyRefundOrderNotify");

        dyRefundOrder.setRefund_related_order_detail(refundRelatedOrderDetails);
//        dyRefundOrder.setRefund_total_amount((int)(orderPo.getTotalPrice()*100));
        orderPo.setWxOutRefundNo(refundNo);
        // 更新dy的退款的id
        orderService.updateById(orderPo);
        BrandPo brandPo = getBrandPo(orderPo);
        JSONObject result = JSONObject.parseObject(postRequest(DyConstant.REFUND_POST, dyRefundOrder, brandPo.getAccountid()));
        log.info("订单id:{},抖音退款结果：{}", orderPo.getId(), result);
        return result;
    }

    //根据bookId取消预约单
    public String userCancelBookPost(OrderPo orderPo){
        String resultCancelBookPost=dyBookRequest.userCancelBookPost1(orderPo);
        log.info("取消预约结果"+resultCancelBookPost);
        return resultCancelBookPost;
    }

    /**
     * 不走协同退老代码 ，需要先调用取消预约在进行退款
     */
    public JSONObject refund2(OrderPo orderPo) {
        log.info("调用主订单退款");
        //调用取消预约
        String resultCancelBookPost=dyBookRequest.userCancelBookPost1(orderPo);
        log.info("取消预约结果"+resultCancelBookPost);
        ThreadUtil.safeSleep(5000);

        DyRefundOrder2 dyRefundOrder = new DyRefundOrder2();
        dyRefundOrder.setOut_order_no(orderPo.getOrderNo());

        String refundNo = orderPo.getOrderNo() + "_" + WsRandomUtil.generateByRandom(10);
        dyRefundOrder.setOut_refund_no(refundNo);
        // 退款单的跳转的 schema
        DyRefundOrder2.OrderEntrySchema orderEntrySchema = new DyRefundOrder2.OrderEntrySchema();
        orderEntrySchema.setPath("pages/order/detail/detail?id=" + orderPo.getId());
        JSONObject params = new JSONObject();
        params.put("id", orderPo.getId());
        orderEntrySchema.setParams(params.toString());
        dyRefundOrder.setOrder_entry_schema(orderEntrySchema);

        // 需要发起退款的商品单信息,子订单
        List<OrderGoodPo> orderGoodPoList = orderGoodService.getOrderGoods(orderPo.getId());
        List<DyRefundOrder2.ItemOrderDetail2> itemOrderDetailList = new ArrayList<>(orderGoodPoList.size());
        for (OrderGoodPo orderGoodPo : orderGoodPoList) {
            DyRefundOrder2.ItemOrderDetail2 ItemOrderDetail2 = new DyRefundOrder2.ItemOrderDetail2();
            ItemOrderDetail2.setItem_order_id(orderGoodPo.getItemOrderId());
            ItemOrderDetail2.setRefund_amount((int) (orderGoodPo.getPrice() * 100));  //抖音这里是做了拆单，预下单这里需要注意，要拆成子订单下单，因此删除了数量
            itemOrderDetailList.add(ItemOrderDetail2);
        }
        dyRefundOrder.setItem_order_detail(itemOrderDetailList);
        dyRefundOrder.setNotify_url("https://www.shoeswasher.com/prod-api/common/dyCallBlack/dyRefundOrderNotify");
//        dyRefundOrder.setRefund_total_amount((int)(orderPo.getTotalPrice()*100));
        orderPo.setWxOutRefundNo(refundNo);
        // 更新dy的退款的id
        orderService.updateById(orderPo);
        BrandPo brandPo = getBrandPo(orderPo);
        JSONObject result = JSONObject.parseObject(postRequest(DyConstant.REFUND_POST, dyRefundOrder, brandPo.getAccountid()));
        log.info("订单id:{},抖音退款结果：{}", orderPo.getId(), result);
        return result;
    }



    //退款审核接口
    public JSONObject audit(OrderPo orderPo) {
        Map<String, Object> params = new HashMap<>();
        params.put("out_refund_no", orderPo.getOrderNo());
        params.put("refund_audit_status", 1);
        params.put("deny_message", "同意退款");
        BrandPo brandPo = getBrandPo(orderPo);
        return JSONObject.parseObject(postRequest(DyConstant.MERCHANT_AUDIT_CALLBACK, params, brandPo.getAccountid()));
    }
}